<template>
  <div>
    <upload-excel-component
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    />
  </div>
</template>
<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
// import { formatExcelDate } from '@/utils/index.js'
import { importEmployees } from '@/api/employees'

export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 成功读出excel文件的内容
    async handleSuccess({ results, header }) {
      console.log('读出来的excel的内容是', results, header)
      this.tableData = results
      this.tableHeader = header
      const newData = this.transExcel(results, header)
      // eslint-disable-next-line no-unreachable
      await importEmployees(newData)
      this.$message.success('导入成功')

      // console.log('obj' + JSON.stringify(results))
    },
    transExcel(results, header) {
      const mapInfo = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName',
        聘用形式: 'formOfEmployment'
      }
      // const chKeys = Object.keys(results[0])
      return results.map((item) => {
        const obj = {}
        header.forEach((zwkey) => {
          const enkey = mapInfo[zwkey]
          obj[enkey] = item[zwkey]
        })
        return obj
      })
    }
  }
}
</script>
